package com.blog.common.utils;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import org.apache.commons.io.FileUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class ImageUtil {

    public static final int HEIGHT = 210;
    public static final int WIDTH = 280;

    public static final int S_HEIGHT = 70;
    public static final int S_WIDTH = 93;

    /**
     * 图片裁剪(已默认控制宽高)
     *
     * @param inPath       图片路径
     * @param targetWidth  图片宽
     * @param targetHeight 图片高
     * @throws Exception
     */
    public static void imageCut(String inPath, int targetWidth, int targetHeight) {
        if (targetHeight == 0 && targetWidth == 0) {
            Map<String, Long> imgInfo = getImgInfo(inPath);
            targetWidth = Integer.parseInt(imgInfo.get("w").toString());
            targetHeight = Integer.parseInt(imgInfo.get("h").toString());
        }
        FileOutputStream out2 = null;
        if (targetWidth > WIDTH) {

            double num = targetWidth / (double) WIDTH;
            int height = (int) (targetHeight / num);
            try {
                BufferedImage image = ImageIO.read(new FileInputStream(inPath));
                BufferedImage tag = new BufferedImage(WIDTH, height, 5);
                tag.getGraphics().drawImage(image, 0, 0, WIDTH, height, null);
                out2 = new FileOutputStream(inPath);
                JPEGImageEncoder encoder2 = JPEGCodec.createJPEGEncoder(out2);
                JPEGEncodeParam param2 = encoder2
                        .getDefaultJPEGEncodeParam(tag);
                param2.setQuality(0.9f, false);
                encoder2.setJPEGEncodeParam(param2);
                encoder2.encode(tag);
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                if (out2 != null) {
                    try {
                        out2.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }
        }
    }

    /**
     * 图片裁剪  自己指定输出路径
     *
     * @param inPath       图片路径
     * @param targetWidth  图片宽
     * @param targetHeight 图片高
     * @throws Exception
     */
    public static void imageCut(String inPath, String outPath, int targetWidth, int targetHeight) {
        if (targetHeight == 0 && targetWidth == 0) {
            Map<String, Long> imgInfo = getImgInfo(inPath);
            targetWidth = Integer.parseInt(imgInfo.get("w").toString());
            targetHeight = Integer.parseInt(imgInfo.get("h").toString());
        }
        FileOutputStream out2 = null;
        try {
            BufferedImage image = ImageIO.read(new FileInputStream(inPath));
            BufferedImage tag = new BufferedImage(targetWidth, targetHeight, 5);
            tag.getGraphics().drawImage(image, 0, 0, targetWidth, targetHeight, null);
            out2 = new FileOutputStream(outPath);
            JPEGImageEncoder encoder2 = JPEGCodec.createJPEGEncoder(out2);
            JPEGEncodeParam param2 = encoder2.getDefaultJPEGEncodeParam(tag);
            param2.setQuality(0.9f, false);
            encoder2.setJPEGEncodeParam(param2);
            encoder2.encode(tag);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (out2 != null) {
                try {
                    out2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    /**
     * 图片裁剪(由传入的值控制宽高 )
     *
     * @param inPath       图片路径
     * @param targetWidth  图片宽
     * @param targetHeight 图片高
     * @throws Exception
     */
    public static void imgCut(String inPath, int targetWidth, int targetHeight) {
        FileOutputStream out2 = null;
        if (targetWidth > WIDTH) {
            try {
                BufferedImage image = ImageIO.read(new FileInputStream(inPath));
                BufferedImage tag = new BufferedImage(targetWidth,
                        targetHeight, 5);
                tag.getGraphics().drawImage(image, 0, 0, WIDTH, targetHeight,
                        null);
                out2 = new FileOutputStream(inPath);
                JPEGImageEncoder encoder2 = JPEGCodec.createJPEGEncoder(out2);
                JPEGEncodeParam param2 = encoder2
                        .getDefaultJPEGEncodeParam(tag);
                param2.setQuality(0.9f, false);
                encoder2.setJPEGEncodeParam(param2);
                encoder2.encode(tag);
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                if (out2 != null) {
                    try {
                        out2.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }
        }
    }

    /**
     * 图片裁剪(强制性裁剪 小图片)
     *
     * @param inPath 图片路径
     *               图片高
     * @throws Exception
     */
    public static void imgCutSmall(String inPath) {
        FileOutputStream out2 = null;
        try {
            BufferedImage image = ImageIO.read(new FileInputStream(inPath));
            BufferedImage tag = new BufferedImage(S_WIDTH, S_HEIGHT, 5);
            tag.getGraphics().drawImage(image, 0, 0, S_WIDTH, S_HEIGHT, null);
            out2 = new FileOutputStream(inPath);
            JPEGImageEncoder encoder2 = JPEGCodec.createJPEGEncoder(out2);
            JPEGEncodeParam param2 = encoder2.getDefaultJPEGEncodeParam(tag);
            param2.setQuality(0.9f, false);
            encoder2.setJPEGEncodeParam(param2);
            encoder2.encode(tag);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (out2 != null) {
                try {
                    out2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    /**
     * 计算图片尺寸大小等信息：w宽、h高、s大小。异常时返回null。
     *
     * @param imgpath 图片路径
     * @return 图片信息map
     */
    public static Map<String, Long> getImgInfo(String imgpath) {
        Map<String, Long> map = new HashMap<String, Long>(3);
        return getImgInfo(new File(imgpath));
    }

    /**
     * 计算图片尺寸大小等信息：w宽、h高、s大小。异常时返回null。
     * <p/>
     * 图片路径
     *
     * @return 图片信息map
     */
    public static Map<String, Long> getImgInfo(File imgfile) {
        Map<String, Long> map = new HashMap<String, Long>(3);
        FileInputStream fis;
        try {
            fis = new FileInputStream(imgfile);
            BufferedImage buff = ImageIO.read(imgfile);
            map.put("w", buff.getWidth() * 1L);
            map.put("h", buff.getHeight() * 1L);
            map.put("s", imgfile.length());
            fis.close();
        } catch (FileNotFoundException e) {
            System.err.println("所给的图片文件" + imgfile.getPath()
                    + "不存在！计算图片尺寸大小信息失败！");
            map = null;
        } catch (IOException e) {
            System.err.println("计算图片" + imgfile.getPath() + "尺寸大小信息失败！");
            map = null;
        } finally {
        }
        return map;
    }

    /**
     * 上传图片
     *
     * @param file     图片文件
     * @param fileName 文件名(当名称为NULL时,将自动生成UUID文件名称)
     * @param width    宽
     * @param height   高
     * @param savePath 保存路径(相对路径,如:"savePath" or "savePath/")
     * @param filemat  保存格式(默认为GIF)
     * @return
     */
    public static String updateFile(File file, String fileName, int width,
                                    int height, String savePath, String filemat) {

        if (fileName == null) {
            fileName = UUID.randomUUID().toString();
        }
        if (filemat == null)
            filemat = ".gif";
        // 日期格式化，用于生成文件夹名
        String dateFormat = DateUtil.getCurrentTime("yyyyMMdd");

        // 判断最后字符是否为'/'
        if (savePath.lastIndexOf("/") != (savePath.length() - 1)) {
            savePath += "/";
        }

        // 图片保存路径
        String folder = "/ichefeng" + savePath + dateFormat + "/";
        // 生成文件夹
        // String targetDirectory = ServletActionContext.getServletContext()
        // .getRealPath(folder);
        File target = new File(folder, fileName + filemat);
        // 图片路径
        String imgUrl = savePath + dateFormat + "/" + fileName + filemat;
        // 复制文件
        try {
            FileUtils.copyFile(file, target);
        } catch (IOException e) {
            // log.error(Result.getMsgCode(ConfigCode.FILE_ERROR).getDetail(),
            // e);
            e.printStackTrace();
        }
        // 图片大小处理
        imgCut(target.getPath(), width, height);
        return imgUrl;
    }

    public static void cutImage(String srcFile,String outPath,int minWidth){
        Map<String, Long> imgInfo = getImgInfo(srcFile);

        //获取源文件宽高
        int targetWidth = Integer.parseInt(imgInfo.get("w").toString());
        int targetHeight = Integer.parseInt(imgInfo.get("h").toString());
        if (targetWidth > minWidth) {
            FileOutputStream out2 = null;
            double num = targetWidth / (double) minWidth;
            int height = (int) (targetHeight / num);
            try {
                BufferedImage image = ImageIO.read(new FileInputStream(srcFile));
                BufferedImage tag = new BufferedImage(minWidth, height, 5);
                tag.getGraphics().drawImage(image, 0, 0, minWidth, height, null);
                out2 = new FileOutputStream(outPath);
                JPEGImageEncoder encoder2 = JPEGCodec.createJPEGEncoder(out2);
                JPEGEncodeParam param2 = encoder2
                        .getDefaultJPEGEncodeParam(tag);
                param2.setQuality(0.9f, false);
                encoder2.setJPEGEncodeParam(param2);
                encoder2.encode(tag);
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                if (out2 != null) {
                    try {
                        out2.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }
        }
    }
}
